package com.zelin;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.hibernate.validator.constraints.br.TituloEleitoral;
import org.junit.Test;

import java.util.Date;

/**
 * Created by WF on 2020/4/3 15:28
 * 对token的基本操作
 */
public class JWTBaseDemo {
    //1.修建jwt
    @Test
    public void test01(){
        //1.1)得到jwtBuilder对象
        //说明：
        //1.Jwts.builder():代表jwt生成器
        //2.setId():设置生成器的id
        //3.setIssuedAt():设置加密时间
        //4.setSubject():设置主体信息
        //signWith:设置jwt的签名
        //5.compact()：得到jwt生成的字符串
        JwtBuilder jwtBuilder =
                Jwts.builder().setId("9999")
                .setIssuedAt(new Date())
                .setSubject("admin")
                .signWith(SignatureAlgorithm.HS256, "zelin");
        //1.2)得到token对象
        String token = jwtBuilder.compact();
        //1.3)打印
        System.out.println("token = " + token);

    }
    //2.解析指定的token
    @Test
    public void test02(){
        //2.1)定义要解析的token字符串
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5OTk5IiwiaWF0IjoxNTg1ODk5MDk5LCJzdWIiOiJhZG1pbiJ9.PToTkCoTJDLpP0hfsukUHtGc5TJRiP1ByoLJPV95vEY";
        //2.2)定义解析token的对象
        Claims claims = Jwts.parser().setSigningKey("zelin")
                .parseClaimsJws(token).getBody();
        String id = claims.getId();
        String subject = claims.getSubject();
        Date issuedAt = claims.getIssuedAt();
        System.out.println("id = " + id);
        System.out.println("subject = " + subject);
        System.out.println("issuedAt = " + issuedAt);
    }
}
